package com.wn.main.ui.category

import android.annotation.SuppressLint
import android.util.SparseArray
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager2.widget.ViewPager2
import com.blankj.utilcode.util.GsonUtils
import com.wn.common.model.CategoryItem
import com.wn.framework.adapter.ViewPage2FragmentAdapter
import com.wn.framework.base.BaseFragment
import com.wn.main.R
import com.wn.main.databinding.FragmentCategoryBinding
import com.wn.main.ui.category.adapter.CategoryTabAdapter
import com.wn.main.ui.category.view.CategoryViewPagerFragment
import com.wn.main.ui.category.viewmodel.CategoryViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * @Author: wn
 * @Date: 2025/2/11 16:18
 * @Description: 分类页面 -- 抽屉模式分类选择
 */
@AndroidEntryPoint
class CategoryFragment : BaseFragment<FragmentCategoryBinding>() {

  override fun getLayoutRes() = R.layout.fragment_category

  private val viewModel by viewModels<CategoryViewModel>()

  // 当前选中的 position
  private var mCurrentSelectPosition = 0
  private var fragments = SparseArray<Fragment>()

  @Inject
  lateinit var mTabAdapter: CategoryTabAdapter

  private val mViewPagerAdapter by lazy {
    ViewPage2FragmentAdapter(childFragmentManager, lifecycle, fragments)
  }

  override fun initView() {
    initTabRecyclerView()
    initViewPager2()
  }

  private lateinit var job: Job
  override fun initData() {
    if (::job.isInitialized) job.cancel()

    job = lifecycleScope.launch {
      lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
        // 获取分类信息
        launch {
          viewModel.getCategoryData().collect {
            // 空 骨架屏
            mBinding.viewEmptyData.isVisible = it.isNullOrEmpty()
            it ?: return@collect
            initCategoryUI(it)
          }
        }
        // 加载 loading
        launch {
          // delay(20) // 确保 loading 先为 true-->控制 刷新
          viewModel.loading.collect {
            if (it) showLoading() else dismissLoading()
          }
        }
      }
    }
  }

  /**
   * 初始化分类 UI
   * @param list MutableList<CategoryItem>
   */
  private fun initCategoryUI(list: MutableList<CategoryItem>) {
    // 默认第一条选中
    list.firstOrNull()?.isSelected = true
    // 左侧列表渲染
    mTabAdapter.setData(list)
    // 右侧 viewPager2 渲染
    list.forEachIndexed { index, item ->
      // bean 转 String
      val fragment = CategoryViewPagerFragment.newInstance(GsonUtils.toJson(item.articles))
      fragments.append(index, fragment)
    }
    // 刷新 viewPager2 ,起始的位置 , 更改的数量
    mViewPagerAdapter.notifyItemRangeChanged(0, list.size)
  }

  /**
   * 左侧 分类列表
   */
  private fun initTabRecyclerView() {
    mBinding.tabRecyclerView.apply {
      layoutManager = LinearLayoutManager(requireContext())
      adapter = mTabAdapter
    }
    // 点击 list 更新 list  同步 更新 viewpager2
    mTabAdapter.onItemClickListener = { _, position: Int ->
      updateTabItem(position)
      mBinding.viewPager2.setCurrentItem(position, false)
    }
  }

  /**
   * 右侧 内容 ViewPager2
   */
  private fun initViewPager2() {
    mBinding.viewPager2.apply {
      offscreenPageLimit = ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT
      orientation = ViewPager2.ORIENTATION_VERTICAL
      adapter = mViewPagerAdapter
      registerOnPageChangeCallback(viewPager2Callback)
    }
  }

  /**
   * 滑动 viewpager2 更新 tab
   */
  private val viewPager2Callback = object : ViewPager2.OnPageChangeCallback() {
    override fun onPageSelected(position: Int) {
      super.onPageSelected(position)
      updateTabItem(position)
    }
  }

  /**
   * Home键或者锁屏 后 如果不 cancel 返回时数据会重复请求  -- stop
   * viewPager 滑动 -- pause
   */
  override fun onStop() {
    if (::job.isInitialized) job.cancel()
    super.onStop()
  }

  override fun onDestroyView() {
    mBinding.viewPager2.unregisterOnPageChangeCallback(viewPager2Callback)
    super.onDestroyView()
  }

  /**
   * 更新Tab状态
   * @param position Int  -- 选中的 位置
   * 1 更新当前选中的 item 2 滑动到当前选中的 item
   */
  @SuppressLint("NotifyDataSetChanged")
  private fun updateTabItem(position: Int) {
    // 重复点击 无需操作
    if (mCurrentSelectPosition == position) return
    mTabAdapter.apply {
      // 修改 list 颜色
      setCurrentPosition(position)
      // 更新上一条item
      val oldItem = getItem(mCurrentSelectPosition)
      oldItem?.apply { isSelected = false }
      // 更新当前item
      val newItem = getItem(position)
      newItem?.apply { isSelected = true }
      // 修改 mCurrentSelectPosition
      mCurrentSelectPosition = position
      // 修改了 item 这里需要 notifyDataSetChanged 重新绘制 List
      notifyDataSetChanged()
    }
    // 移动到 选中的位置
    mBinding.tabRecyclerView.smoothScrollToPosition(position)
  }
}